namespace Ultimate.League.Controls
{
	using System;
	using System.Data;
	using System.Drawing;
	using System.Web;
	using System.Web.UI.WebControls;
	using System.Web.UI.HtmlControls;

    using System.Collections;
	using System.Text;
	
	using Ultimate.DAL.CollectionClasses;
	using Ultimate.DAL;
	using Ultimate.DAL.HelperClasses;
	using Ultimate.DAL.EntityClasses;
	using Ultimate.DAL.FactoryClasses;
	using SD.LLBLGen.Pro.ORMSupportClasses;

    using CommunityServer.Components;

	/// <summary>
	/// This control is used to edit or view a league
	/// </summary>
	public class EditLeague : System.Web.UI.UserControl
	{
		protected System.Web.UI.WebControls.TextBox LeagueName;
        protected System.Web.UI.WebControls.Button SaveButton;
		protected System.Web.UI.WebControls.DataGrid dgTeams;
		protected System.Web.UI.WebControls.DropDownList UnassignedTeams;
		protected System.Web.UI.WebControls.Button Button2;
		protected System.Web.UI.WebControls.TextBox Name;
		protected System.Web.UI.WebControls.CheckBox ResgistrationOpen;
		protected System.Web.UI.WebControls.TextBox Info;
		protected System.Web.UI.WebControls.CheckBox RegistrationOpen;
		protected System.Web.UI.WebControls.Panel LeagueDetails;
		protected System.Web.UI.WebControls.Literal LeagueNameHeader;
		protected System.Web.UI.WebControls.TextBox TeamFee;
		protected System.Web.UI.WebControls.TextBox PlayerFee;
		protected System.Web.UI.WebControls.LinkButton LinkButton1;
		protected System.Web.UI.WebControls.LinkButton Linkbutton2;
		protected System.Web.UI.WebControls.Panel Teams;
		protected System.Web.UI.WebControls.Literal Captains;
		protected System.Web.UI.WebControls.Literal Rosters;
		protected System.Web.UI.WebControls.Label LeagueID2;
        protected System.Web.UI.WebControls.DropDownList RoleName;
        protected System.Web.UI.WebControls.DataGrid Report;

        protected System.Web.UI.WebControls.Literal TeamsCount;
		/// <summary>
		/// Could be used to set the leagueID through code instead of query sring.  Persists the league ID in ViewState
		/// </summary>
		public int LeagueID
		{
			get
			{
				return Convert.ToInt32(ViewState["LeagueID"]);
			}
			set
			{
				ViewState["LeagueID"] = value;
			}
		}
		/// <summary>
		/// Checks security and binds the data on first load
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void Page_Load(object sender, System.EventArgs e)
        {
            
			
			if (!this.IsPostBack)
			{
                //load the role name drop list
                ArrayList rolesList = CommunityServer.Components.Roles.GetRoles(0, false, false);
                RoleName.DataTextField = "Name";
                RoleName.DataValueField = "Name";
                RoleName.DataSource = rolesList;
                RoleName.DataBind();
                
				//if (!Context.User.IsInRole(SecurityLevel.Admin.ToString()))Response.Redirect("~",true);
                
                LeagueID = -1;
                if (Request.QueryString["LeagueID"] != null)
                {
                    LeagueID = Convert.ToInt32(Request.QueryString["LeagueID"]);
                    
                    BindData();                   

                    if (CheckSecurity())
                    {
                        
                        LeagueDetails.Visible = true;
                        dgTeams.Columns[1].Visible = true;
                        dgTeams.Columns[2].Visible = true;

                    }
                }
                else if (CSContext.Current.User.IsInRoles(new string[] {"LeagueAdministrator"}))
                {
                    
                    LeagueDetails.Visible = true;
                    dgTeams.Columns[1].Visible = true;
                    dgTeams.Columns[2].Visible = true;
                }
			}
		}

		/// <summary>
		/// Uses auto bind to bind the data
		/// Also binds the datagrid.
		/// </summary>
		private void BindData()
		{
            
            LeagueEntity le = new LeagueEntity(LeagueID);
			LeagueNameHeader.Text=le.Name;
			Ultimate.AutoBind.BindObjectToControls(le,this);
			LeagueID2.Text=le.LeagueID.ToString();

            TeamCollection teams = new TeamCollection();
            ISortExpression sorter = new SortExpression(SortClauseFactory.Create(TeamFieldIndex.Grouping, SortOperator.Ascending));
            sorter.Add(SortClauseFactory.Create(TeamFieldIndex.TeamName, SortOperator.Ascending));
            PredicateExpression filter = new PredicateExpression(
                PredicateFactory.CompareValue(TeamFieldIndex.LeagueID,
                ComparisonOperator.Equal,
                le.LeagueID));

            teams.GetMulti(filter, 0, sorter);

            dgTeams.DataSource = teams;
			dgTeams.DataBind();
            TeamsCount.Text = "# of Teams: " + le.Team.Count.ToString();
			
		}
		/// <summary>
		/// Uses autobind to save the data to the database
		/// </summary>
		/// <param name="o"></param>
		/// <param name="e"></param>
		protected void SaveLeague(object o,EventArgs e)
		{
            if(!CheckSecurity())
            {
                throw new System.Security.SecurityException("You do not have permissions to edit this league");
            }
			AutoBind.BindControlsToObject(CurrentLeague,this);
            //Response.Write("Saving as: " + RoleName.SelectedValue);
            bool shouldRedirect = CurrentLeague.IsNew;

            CurrentLeague.RoleName = RoleName.SelectedValue;
			CurrentLeague.Save();

            if (shouldRedirect)
            {
                Response.Redirect(Request.Url.ToString() + "?LeagueID=" + CurrentLeague.LeagueID.ToString());
            }

		}

		/// <summary>
		/// Used to remove a team from the league.
		/// Takes all the players on the team and moves them to the individuals team, deletes the team.
		/// </summary>
		/// <param name="o"></param>
		/// <param name="e"></param>
		protected void RemoveTeam(object o,DataGridCommandEventArgs e)
		{
            if (CheckSecurity())
            {
                int teamID = Convert.ToInt32(dgTeams.DataKeys[e.Item.DataSetIndex]);
                TeamEntity te = new TeamEntity(teamID);
                te.SetNewFieldValue((int)TeamFieldIndex.LeagueID, null);
                int individualTeamID = GetIndivudalsTeamID();
                if (individualTeamID > 0)
                {
                    foreach (PlayerEntity pe in te.PlayerCollectionViaTeamPlayer)
                    {
                        TeamPlayerEntity tpe = new TeamPlayerEntity(teamID,pe.UserID);
                        tpe.TeamID = individualTeamID;
                        tpe.RoleID = (int)Ultimate.Roles.Individual;
                        tpe.Save();
                    }
                }
                te.TeamPlayer.DeleteMulti();
                te.Delete();
                BindData();
            }
		}

        /// <summary>
        /// Check to see if the user is allowed permission to edit things
        /// </summary>
        /// <returns></returns>
        private bool CheckSecurity()
        {
            bool roleAllowed = true;
            if(!CurrentLeague.IsNew)
                roleAllowed = System.Web.Security.Roles.IsUserInRole(CurrentLeague.RoleName);
            return (roleAllowed || CSContext.Current.User.IsRegistrationAdministrator);
        }

        private LeagueEntity _currentLeague;
        /// <summary>
        /// Gets teh Current League being administered.
        /// </summary>
        private LeagueEntity CurrentLeague
        {
            get
            {
                if (_currentLeague == null)
                {
                    if (LeagueID == -1)
                    {
                        _currentLeague = new LeagueEntity();
                    }
                    else
                    {
                        _currentLeague = new LeagueEntity(LeagueID);
                    }
                }

                return _currentLeague;
            }
        }



		protected void ShowCaptains(object o,System.EventArgs e)
		{
			StringBuilder sb = new StringBuilder();
			DAL.TypedListClasses.PlayerTeamLeagueTypedList ptl = new DAL.TypedListClasses.PlayerTeamLeagueTypedList();
			PredicateExpression A = new PredicateExpression();
			A.Add(PredicateFactory.CompareValue(TeamFieldIndex.LeagueID, ComparisonOperator.Equal, this.LeagueID));
            A.Add(PredicateFactory.CompareValue(TeamPlayerFieldIndex.RoleID, ComparisonOperator.Equal, (int)Ultimate.Roles.Captain));
			ISortExpression sorter = new SortExpression(SortClauseFactory.Create(TeamFieldIndex.TeamName,SortOperator.Ascending));
			ptl.Fill(0,sorter,false,A);
			
			string currentTeam="";
			bool firstRun=true;
			foreach(DAL.TypedListClasses.PlayerTeamLeagueRow row in ptl.Rows)
			{
				if (currentTeam != row.TeamName)
				{
					currentTeam = row.TeamName;
					if (!firstRun)sb.Append("</table>");
					firstRun = false;
					sb.Append("<h3>"+row.TeamName+"</h3><table>");
				}
				sb.Append("<tr><td>"+row.TeamName+"<td>");
				sb.Append("<td>"+row.UserName+"<td>");
				sb.Append("<td>"+row.Email+"</td>");
				sb.Append("<td>"+row.PhoneNumber+"</td></tr>");
			}
			sb.Append("</table>");
			Captains.Text=sb.ToString();
			
			Rosters.Text="";
			Teams.Visible=false;
			LeagueDetails.Visible=false;
			
			
		}
		protected void ShowRosters(object o,System.EventArgs e)
		{
			StringBuilder sb = new StringBuilder();
			DAL.TypedListClasses.PlayerTeamLeagueTypedList ptl = new DAL.TypedListClasses.PlayerTeamLeagueTypedList();
			PredicateExpression A = new PredicateExpression();
			A.Add(PredicateFactory.CompareValue(TeamFieldIndex.LeagueID, ComparisonOperator.Equal, this.LeagueID));
			
			ISortExpression sorter = new SortExpression(SortClauseFactory.Create(TeamFieldIndex.TeamName,SortOperator.Ascending));

            sorter.Add(SortClauseFactory.Create(TeamPlayerFieldIndex.RoleID, SortOperator.Ascending));
            sorter.Add(SortClauseFactory.Create(PlayerFieldIndex.LastName, SortOperator.Ascending));
			ptl.Fill(0,sorter,false,A);
			
			string currentTeam="";
			bool firstRun=true;
			foreach(DAL.TypedListClasses.PlayerTeamLeagueRow row in ptl.Rows)
			{
				if (currentTeam != row.TeamName)
				{
					currentTeam = row.TeamName;
					if (!firstRun)sb.Append("</table>");
					firstRun = false;
					sb.Append("<h3>"+row.TeamName+"</h3><table>");
				}
				sb.Append("<td>");
                if (row.RoleID == (int)Ultimate.Roles.Captain) sb.Append("C&nbsp;");
				sb.Append(row.UserName+"<td>");
				sb.Append("<td>"+row.Email+"</td>");
				sb.Append("<td>"+row.PhoneNumber+"</td></tr>");
			}
			sb.Append("</table>");
			
			Rosters.Text=sb.ToString();
			Captains.Text="";
			Teams.Visible=false;
			LeagueDetails.Visible=false;
			
		}
		/// <summary>
		/// Gets the id of the "individuals" team for the current league or returns -1 if there is none
		/// </summary>
		/// <returns>Individuals team id or -1 if none</returns>
		protected int GetIndivudalsTeamID()
		{

			TeamCollection tc = new TeamCollection();
			PredicateExpression A = new PredicateExpression();
			A.Add(PredicateFactory.CompareValue(TeamFieldIndex.LeagueID , ComparisonOperator.Equal, Convert.ToInt32(this.LeagueID) ));
			A.AddWithAnd(PredicateFactory.CompareValue(TeamFieldIndex.TeamName  , ComparisonOperator.Equal, "Individuals"));
			tc.GetMulti(A);
			if (tc.Count >0)
			{
				return (tc[0].TeamID);
			}
			else return -1;
		}
        protected void ShowReport(object o, System.EventArgs e)
        {
            Report.DataSource = DAL.StoredProcedureCallerClasses.RetrievalProcedures.LeagueReport(this.LeagueID);
            Report.DataBind();
            Report.Visible = true;
        }

        private string _editGamesUrl = "~/RegistrationSystem/League/SetupGames.aspx?";
        public string EditGamesUrl
        {
            get
            {
                return _editGamesUrl;
            }
            set
            {
                _editGamesUrl = value;
            }
        }
        protected void EditGames(object o, System.EventArgs e)
        {
            Response.Redirect(EditGamesUrl + "LeagueID=" + this.LeagueID.ToString(), true);
        }

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion


        private string _editTeamUrl = "~/RegistrationSystem/Team/EditTeam.aspx?";
        public string EditTeamUrl
        {
            get
            {
                return _editTeamUrl;
            }
            set
            {
                _editTeamUrl = value;
            }
        }
        protected MultiView MultiView1;

        protected void btnTeams_Click(object sender, EventArgs e)
        {
            MultiView1.ActiveViewIndex = 1;
        }

        protected void btnSettings_Click(object sender, EventArgs e)
        {
            MultiView1.ActiveViewIndex = 0;
        }
	}
}
